import React, {Component} from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Platform,
  StyleSheet,
  ActivityIndicator,
  Image,
  ListView,
  RefreshControl
} from 'react-native'
import {Actions} from "react-native-router-flux";
import {ListRow, Toast} from 'teaset'
import * as String from './../../utils/srting'
import font from './../../styles/font'
import Toast2, {
  DURATION
} from 'react-native-easy-toast'
import { SafeAreaView } from 'react-navigation';

class UserHistoryScene extends Component{
  constructor(props){
    super(props)
    this.ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      dataSource: this.ds.cloneWithRows([]),
      jifen: '',
      isRefreshing: false
    }
  }

  componentDidMount() {
    this.props.actions.getUserHistory()
  }

  componentWillReceiveProps(nextProps) {
    const {
      userHistory,
    } = nextProps;

    if(this.props.userHistory !== userHistory){
      this.setState({isRefreshing: false});
      if (userHistory.error !== false) {
        if (userHistory.error.status === 401) {
          if(global.isWXAppInstalled){
            Actions.login()
            return;
          }
        }
        this.toast.show(userHistory.error.message)
      }else{
        if(userHistory.data && userHistory.data.length > 0){
          this._setRows(userHistory.data);
          this.setState({
            dataSource: this.ds.cloneWithRows(this._getRows()),
          });
        }
      }
    }
  }


  _setRows(rows) {
    this._rows = rows;
  }
  _getRows() {
    return this._rows ? this._rows : [];
  }

  _onRefresh(){
    this.setState({isRefreshing: true});
    this.props.actions.getUserHistory()
  }


  renderRow(userHistory){
    return(
      <ListRow
        topSeparator = 'full'
        bottomSeparator = 'full'
        onPress={()=>{ Actions.taoBaoWeb({...userHistory})}}
        title={<Image style={styles.itemImg} source={{uri:userHistory.pictUrl}}/>}
        detail={
          <View style={styles.content}>
            <Text style={font.black18} numberOfLines={1}>{userHistory.title}</Text>
            <Text style={styles.itemText}>券<Text style={styles.itemText2}>{userHistory.couponAmount}</Text>元
              <Text style={styles.itemText}>现价<Text style={styles.itemText2}>￥{userHistory.zkPrice} </Text>
                <Text style={styles.itemText}>月销<Text style={styles.itemText2}>{userHistory.biz30day} </Text>
                  件
                </Text>
              </Text>
            </Text>
          </View>
        }
      />
    )
  }


  render(){

    const { error, data } = this.props.userHistory
    if(error && error.status === 401) {

      if (global.isWXAppInstalled) {
        // if(true){
        return (
          <View style={{flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff'}}>
            <TouchableOpacity onPress={() => {
              Actions.login()
            }}>
              <Text style={{color: '#000', fontSize: 16}}>立即登录</Text>
            </TouchableOpacity>
          </View>
        )
      } else {
        return (
          <View style={{flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff'}}>
            <Text style={{color: '#000', fontSize: 16}}>暂无收藏记录</Text>
          </View>
        )
      }

    }else{
      return(
        <SafeAreaView style={styles.container}>
          <View style={styles.title}>
            <Text>我的浏览记录</Text>
          </View>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={(rowData) => this.renderRow(rowData)}
            enableEmptySections={true}
            refreshControl={
              <RefreshControl
                refreshing={this.state.isRefreshing}
                onRefresh={this._onRefresh.bind(this)}
                tintColor="#000"
                title="正在刷新"
                titleColor="#000"
                colors={['#000']}
                progressBackgroundColor="#fff"
              />
            }
          />
          <Toast2
            ref={view => this.toast = view}
            style={{backgroundColor:'red'}}
            opacity={0.6}
            position='top'/>
        </SafeAreaView>
      )
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#fff'
  },
  title:{
    height:40,
    flexDirection:'row',
    marginLeft:10,
    marginBottom:10,
    alignItems:'center',
  },
  itemContainer:{
    borderTopColor:'#f6f6f6',
    borderTopWidth:1,
    flexDirection:'row',
  },
  itemImg:{
    width:60,
    height:60,
    margin:10
  },
  content:{
    flex:1,
    paddingVertical:5,
    justifyContent:'center',
  },
  itemText:{
    color:'#999',
    fontSize:14,
  },
  itemText2:{
    color:'#f00',
    fontSize:14,
  }
})


export const LayoutComponent = UserHistoryScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    userHistory: state.userHistoryReducer,
  }
}